<template>
  <div>
  <h3 v-if="this.auth === '0'" style="vertical-align: middle; margin-top: 10px; margin-left: 20px;">您不是管理员，没有访问权限!!!</h3>
  <div class="register-container" v-if="(this.auth === '2')||(this.auth === '1')">
    <el-form ref="adminForm" label-width="150px" class="register-form" :model="adminInfo" :rules="rules" autocomplete="false" >
      <el-form-item label="用户类型" prop="accountType">
        <el-select ref="elSelect1" v-model="adminInfo.accountType" placeholder="请选择用户类型" style="width: 450px">
          <el-option label="超级管理员" value="2" v-if="(this.auth === '2'&&(this.$route.params && this.$route.params.id))"></el-option>
          <el-option label="管理员" value="1" v-if="(this.auth === '2')"></el-option>
          <el-option label="操作员" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="adminInfo.username"  @blur="usernameVerification()"
                  autocomplete="off"
                  :readonly="readonlyInput"
                  @focus="cancelReadOnly()"
                  onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password"  autocomplete="off" v-model="adminInfo.password" auto-complete="new-password"></el-input>
      </el-form-item >
      <el-form-item label="确认密码" autocomplete="off" prop="confirmPassword" v-if="!(adminInfo.adminId)">
        <el-input type="password" v-model="adminInfo.confirmPassword" v-if="!(adminInfo.adminId)"></el-input>
      </el-form-item>
      <el-form-item label="管理员姓名" prop="adminName">
        <el-input v-model="adminInfo.adminName"></el-input>
      </el-form-item>
      <el-form-item label="授权登记机关" prop="licence42Code" >
        <div class="block">
          <span class="demonstration"></span>
          <el-cascader
            :options="options"
            :props="props"
            collapse-tags
            clearable
            v-model="adminInfo.licence42Code"
            style=" width: 450px"
            ref="cascader"
          ></el-cascader>
        </div>
      </el-form-item>
      <el-form-item style="margin-left: 140px">
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
        <el-button v-if="!(adminInfo.adminId)" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  </div>
</template>

<script>
import { register } from "@/api/admin/register";
import { getList } from "../../api/admin/register";
import editApi from "@/api/admin/edit";
import {myLogout} from "@/api/login";

export default {
  data() {
    return {

      readonlyInput: true,

      flag: true,
      auth: '',
      adminInfo: {
      },
      rules: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'},
          {min: 5, max:50, message: '用户名不能少于5位,且由数字、字母、符号组成', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 5,  max:50, message: '密码长度在6到20个字符之间', trigger: 'blur'}
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.adminInfo.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        adminName: [
          {required: true, message: '管理员姓名不能为空', trigger: 'blur'}
        ],
        licence42Code: [
          {required: true, message: '授权登记机关不能为空', trigger: 'blur'}
        ],
        accountType: [
          {required: true, message: '请选择用户类型', trigger: 'change'}
        ],
      },
      props: {multiple: false},
      options: []
    };
  },
  created() {
    // 获取路由id值 调用接口得到管理员信息
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id
      this.getAdminInfo(id)
      this.flag = false;
    } else {
      this.adminInfo = {}
      this.flag = true;
    }

    // 获取级联选择器数据
    getList().then(res=>{
      this.options = res.data;
    }).catch(error => {
        console.log(error)
        myLogout();
        this.$store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      }
    )

    // 限制管理员注册其他管理员、超级管理员
    this.getAuthCode();

  },
  watch: {

  },
  mounted() {
    document.addEventListener('click', this.closeCascader.bind(this));
    document.addEventListener('click', this.closeSelect.bind(this));
  },
  methods: {
    cancelReadOnly () {
      this.readonlyInput = false;
    },

    // 选择器收起
    closeCascader(e) {
      if (this.$refs.cascader && !this.$refs.cascader.$el.contains(e.target)) {
        this.$refs.cascader.dropDownVisible = false;
      }
    },
    // 收起select
    closeSelect(e) {
        // this.$refs.elSelect1.handleClose();
    },
    // 验证用户名是否可用
    usernameVerification() {
      if (this.adminInfo.username !== null && this.adminInfo.username!=='') {
        editApi.verUsername(this.adminInfo.username)
          .then(res => {

          }).catch(res => {
            if(this.flag){
              this.$message({
                type: 'error',
                message: '用户名重复，不可用'
              })
            }
        })
      }
    },

    saveOrUpdate() {
      this.$refs.adminForm.validate(valid => {
        if (valid) {
          // 注册
          if (!this.adminInfo.adminId) {
            register(this.adminInfo.username, this.adminInfo.password, this.adminInfo.licence42Code, this.adminInfo.adminName, this.adminInfo.accountType).then(result => {
              this.$message({
                type: 'success',
                message: '添加成功',
              })
              this.$router.push({path: '/admin/edit'})
            }).catch(res => {
              this.$message({
                type: 'error',
                message: '添加失败，用户名重复',
              })
            })
          } else {
            this.updata()
          }
        } else {
          this.$message({
            type: 'error',
            message: '请填写正确的注册信息',
          })
        }
      })

    },
    getAdminInfo(id) {
      editApi.getAdminInfo(id).then(response => this.adminInfo = response.data)
    },
    updata() {
      editApi.updateAdminInfo(this.adminInfo.adminId,this.adminInfo.username, this.adminInfo.password, this.adminInfo.licence42Code, this.adminInfo.adminName, this.adminInfo.accountType)
        .then(result => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.$router.push({path: '/admin/edit'})
        })
    },
    resetForm() {
      this.adminInfo = {};
      this.confirmPassword = "";
    },
    getAuthCode(){
      editApi.getAuth().then(res=>{
        this.auth = res.data;
        if (this.auth === '0') {
          // 如果 auth===0 ，则重定向至 /404 页面
          this.$router.push('/404');
        }
      }).catch(error => {
          console.log(error)
          myLogout();
          this.$store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        }
      )
    }
  }
};

</script>

<style scoped>

.username-exist {
  border-color: red;
  suffix-icon: el-icon-error;
}

.register-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.register-form {
  width: 600px;
}


.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  /* 或者设置margin-top属性 */
  margin-top: 50px;
  margin-left: -130px;
}
</style>
